(function (Topro) {
    //UI命名空间
    var UI = Topro.UI || {};

    /*******************************
    * 重写Ajax
    *******************************/
    UI.Ajax = function (opt) {

        var fn = {
            error: function (XMLHttpRequest, textStatus, errorThrown) { },
            success: function (data, textStatus) { }
        }
        if (opt.error) {
            fn.error = opt.error;
        }
        if (opt.success) {
            fn.success = opt.success;
        }
        var _opt = $.extend(opt, {
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                fn.error(XMLHttpRequest, textStatus, errorThrown);
            },

            success: function (data, textStatus) {
                try {
                    if (data.length < 500) {
                        var dataJson = $.parseJSON(data);
                        if (dataJson.Error) {
                            UI.Alert({ content: dataJson.Message });
                            data = "";
                        }
                    }
                    if (typeof (data) === "object") {
                        if (data.Error) {
                            UI.Alert({ content: data.Message });
                            data = "";
                        }
                    }
                    if (data && data.IsLogout) {
                        eval(data.Callback);
                    }
                } catch (e) {
                }
                fn.success(data, textStatus);
            }
        });
        _opt.data.RequestIndicate = $("#RequestIndicate").val();
        $.ajax(_opt);
    };

    UI.DoSearch = function () {
        window.currentPage = null;
        doSearch();
    }

    /*******************************
    * 系统分页定制插件
    *******************************/
    UI.Pager = function (selector, options) {

        var defaults = {
            totalCount: 0,  //总条数
            totalPages: 0,  //总页数
            pageSize: options.pageSize == null ? 15 : options.pageSize,   //每页显示数
            currentPage: window.currentPage == null ? 1 : window.currentPage, //当前页
            numericPagerItemCount: 8, //每页分页按钮显示数
            additionTotal: 10, //每页显示条数中生成的页码增量(20, 30, 40)
            holder: null,
            templateId: options.templateId, //当类型为json时必须设置模板Id
            afterBindDataEvent: null,
            lang: { //语言
                bar: '条',
                previousPage: '上一页',
                nextPage: '下一页',
                displayPerPage: '每页显示',
                noDataDisplay: '没有数据',
                falseDataNote: '网络是否通畅'
            },
            searchFormID: 'formSearch',
            ajax: //数据源设置 
                {
                    url: null,
                    method: options.ajax.Method == null ? 'Get' : options.ajax.Method,
                    data: {}, //请求参数数据
                    dataType: 'json', //当类型为json时必须设置模板Id,html不用设置
                    contentType: "application/json"
                },
            othersData: options.othersData //增加一个附加参数
        };

        var options = $.extend(true, {}, defaults, options);

        //对象
        selector = $(selector); //一页最少显示的条数，以这个为基数以5向上增加三个
        var basicPageSize = options.pageSize;

        //创建页大小选择控件
        function buildPageSizeSelector(pageSize) {
            pageSize = parseInt(pageSize);
            var sizeArr = [10, 20, 50, 100, 150, 200];
            if (sizeArr.indexOf(pageSize) < 0) {
                sizeArr.push(pageSize);
            }
            var str = "<select class='input-page-size wd60' style='border:1px solid #ccc'>";
            for (var i = 0; i < sizeArr.length; i++) {
                str += "<option" + (sizeArr[i] === pageSize ? " selected='selected'" : "") + ">" + sizeArr[i] + "</option>";
            }
            str += "</select>";
            return str;
        }

        //绑定分页事件
        function bindEvent() {
            var that = selector;

            //绑定下拉
            that.next().find("select").change(function () {
                var pageSize = $(this).children("option:selected").val();
                options.pageSize = pageSize;
                options.currentPage = 1;
                bindData();
            });

            //绑定go事件
            that.next().find(".pagego").click(function () {
                var pageInput = that.next().find(".indexgo");
                var pageIndex = pageInput.val().length === 0 ? options.currentPage : parseInt(pageInput.val());
                if (pageIndex < 1 || pageIndex > options.totalPages)
                    pageIndex = 1;
                options.currentPage = pageIndex;
                bindData();
            });

            //绑定a标签点击事件
            that.each(function () {
                that.next().find("a").click(function () {
                    if (!$(this).parent().hasClass("disabled")) {
                        var clickedLink = $(this).attr("rel");
                        var currentPage = parseInt(clickedLink);
                        options.currentPage = window.currentPage = currentPage;
                        bindData();
                        return false;
                    }
                });
            });

            selector.next().find("li.active a").unbind('click');

            /*处理上一页和下一页事件*/
            if (options.currentPage <= 1) {
                selector.next("li:first a").unbind("click");
            }
            if (options.currentPage >= options.totalPages) {
                selector.next("li:last a").unbind("click");
            }

            return that;
        }
        //绑定数据
        function bindData() {
            var cover = Topro.UI.Mask({ obj: $("body"), opacity: 0.5 });

            var type = options.ajax.method || options.ajax.type;
            var data_param = {};
            var data_form = $("#" + options.searchFormID).serialize();

            //防止出现乱码
            var decode_form = decodeURIComponent(data_form, true);

            //post请求传参与get略有不同
            if (type.toLowerCase() == "post") {
                options.ajax.data.PageIndex = options.currentPage;
                options.ajax.data.PageSize = options.pageSize;
                data_param = $.param(options.ajax.data) + "&" + decode_form + "&" + (options.othersData == undefined ? '' : $.param(options.othersData));
                var params = Topro.Util.parseQueryString2(data_param);
                data_param = JSON.stringify(params);
            } else {
                options.ajax.data.PageIndex = options.currentPage;
                options.ajax.data.pageSize = options.pageSize;
                data_param = $.param(options.ajax.data) + "&" + decode_form;
            }

            var targetData, result = {};
            if (options.ajax.url) {
                Topro.UI.Ajax({
                    type: type,
                    url: options.ajax.url,
                    contentType: options.ajax.contentType,
                    data: data_param,
                    async: false,
                    success: function (data) {

                        result = data;

                        if (options.ajax.dataType === 'json') {
                            var evalText = doT.template($("#" + options.templateId).text());
                            targetData = evalText(data)
                        } else if (options.ajax.dataType === 'html') {
                            targetData = data;
                        }

                        selector.html(data);

                        //取每页显示数
                        var pageSize = options.pageSize;
                        if (pageSize) {
                            options.pageSize = pageSize;
                        }
                        //取分页总数
                        var totalCount = parseInt(selector.find("#TotalCount").val());
                        if (totalCount) {
                            options.totalCount = totalCount;
                            options.totalPages = Math.ceil(options.totalCount / options.pageSize);
                        }


                        pagerBuilder();

                        /*增加加载数据后 处理一些其他事情*/
                        if (options.totalCount != 0 && options.afterBindDataEvent != null && $.isFunction(options.afterBindDataEvent)) {
                            options.afterBindDataEvent();
                        }
                        //resize
                        $(window).resize();
                        //移除遮罩
                        setTimeout(function () {
                            cover.Remove();
                        }, 300);
                        
                        
                    },
                    error: function (e) {
                        if (e.responseText) {
                            //Topro.UI.tip_alert('alert-danger', e.responseText);
                        } else {
                            //Topro.UI.tip_alert('alert-danger', options.lang.falseDataNote);
                        }
                    }
                });
            } else {
                return;
            }
        }

        //生成分页
        function pagerBuilder() {

            var pageIndex = options.currentPage;
            // start page index
            var startPageIndex = pageIndex - (options.numericPagerItemCount / 2);
            if (startPageIndex + options.numericPagerItemCount > options.totalPages)
                startPageIndex = options.totalPages + 1 - options.numericPagerItemCount;
            if (startPageIndex < 1)
                startPageIndex = 1;

            // end page index
            var endPageIndex = startPageIndex + options.numericPagerItemCount - 1;
            if (endPageIndex > options.totalPages)
                endPageIndex = options.totalPages;

            //分页数据
            var pages = [];
            //上一页
            /*if (pageIndex > 1) {
                var previousPage = pageIndex - 1;
                pages.push({ text: options.lang.previousPage, pageIndex: previousPage });
            }*/
            /*上一页始终显示出来*/
            var previousPage = pageIndex - 1;
            pages.push({ text: options.lang.previousPage, pageIndex: previousPage });

            //more before
            var index;
            if (startPageIndex > 1) {
                index = startPageIndex - 1;
                if (index < 1) index = 1;
                pages.push({ text: "&hellip;", pageIndex: index });
            }
            //middle
            for (var i = startPageIndex; i <= endPageIndex; i++) {
                pages.push({ text: i, pageIndex: i });
            }
            //more after
            if (endPageIndex < options.totalPages) {
                index = startPageIndex + options.numericPagerItemCount;
                if (index > options.totalPages) {
                    index = options.totalPages;
                }
                pages.push({ text: "&hellip;", pageIndex: index });
            }
            //下一页
            /*if (pageIndex < options.totalPages) {
                var nextPageIndex = pageIndex + 1;
                pages.push({ text: options.lang.nextPage, pageIndex: nextPageIndex });
            }*/
            /*下一页始终显示出来*/
            var nextPageIndex = pageIndex + 1;
            pages.push({ text: options.lang.nextPage, pageIndex: nextPageIndex });
            //生成html分页 
            var pageNav = "<div class='data-page clearfix'>" +
                "<div class='pull-left'>共" + options.totalCount + "条 每页显示" + options.pageSize + "条</div>" +
                "<div class='pull-right'>" +
                " <ul class='pagination'>";

            for (var p in pages) {
                if (pages.hasOwnProperty(p)) {
                    var $class = "";
                    if (pages[p].pageIndex === pageIndex)
                        $class += "class='active'";
                    if (pages[p].text == "上一页") {
                        $class += "class='last'";
                        pageNav += "<li " + $class + "><a rel='" + pages[p].pageIndex + "' href='javascript:;'>" + pages[p].text + "</a></li>";
                    }
                    else if (pages[p].text == "下一页") {
                        $class += "class='next'";
                        pageNav += "<li " + $class + "><a rel='" + pages[p].pageIndex + "' href='javascript:;'>" + pages[p].text + "</a></li>";
                    } else {
                        pageNav += "<li " + $class + "><a rel='" + pages[p].pageIndex + "' href='javascript:;'>" + pages[p].text + "</a></li>";
                    }
                }
            }
            pageNav += "</ul></div></div>";


            //绑定之前删除
            selector.parent().find(".data-page").remove();
            //绑定分页结果
            selector.after(pageNav);

            /*增加上一页和下一页的样式*/
            if (pageIndex <= 1) {
                selector.next().find("li:first").addClass("disabled");
            }
            if (pageIndex >= options.totalPages) {
                selector.next().find("li:last").addClass("disabled");
            }

            bindEvent();
        }

        bindData();
    };

    /*******************************
    * 关闭弹出框
    @ id:待关闭的对话框ID
           不传则关闭当前弹出的iframe对话框
    *******************************/
    UI.CloseDialog = function (id) {
        if (typeof id !== 'undefined') {
            art.dialog.list[id].close();
        } else {
            art.dialog.close();
        }
    };
    /*******************************
    * 获取弹出该弹出框的父页面window对象
    *******************************/
    UI.DialogOpener = function () {
        return art.dialog.opener;
    };
    /*******************************
    *	弹出提示信息
    *	{
            @ content : 信息内容
            @ callback : 回调函数
            @ width : 对话框宽度,默认200px,内容超过15字可以根据内容长度可适当增加
        }
     *******************************/
    UI.Alert = function (useroptions) {
        var options = $.extend({
            content: '',
            callback: function () {
            },
            width: '200px',
            icon: 'warning'
        }, useroptions);
        return Topro.UI.DialogBox({
            id: 'dialog_alert',
            title: '提示',
            parent: true,
            lock: true,
            fixed: true,
            padding: '20px 15px 20px 10px',
            ok: true,
            width: options.width,
            content: options.content,
            close: options.callback,
            icon: options.icon
        });
    };
    /*******************************
    *	弹出确定信息
    *	{
            @ content : 信息内容
            @ ok : 点击确定后的回调函数
            @ cancel : 点击取消后的回调函数
            @ width : 对话框宽度,默认200px,内容超过15字可以根据内容长度可适当增加
        }
     *******************************/
    UI.Confirm = function (useroptions) {
        var options = $.extend({
            content: '',
            ok: function () {
            },
            cancel: function () {
            },
            id: 'dialog_confirm',
            width: '200px'
        }, useroptions);

        return Topro.UI.DialogBox({
            id: options.id,
            title: '操作',
            parent: true,
            lock: true,
            fixed: true,
            icon: 'question',
            padding: '20px 15px 20px 10px',
            ok: options.ok,
            width: options.width,
            content: options.content,
            cancel: options.cancel
        });
    };
    /*******************************
    * 弹出框
    * @useroptions:用户配置项 详细设置参考:http://www.planeart.cn/demo/artDialog/_doc/API.html
    *                       扩展了 {parent:true/false} 参数,默认true 该参数用来设置获取的dialog对象位置  设置true的时候获取的对象是top  false的时候为self
    *******************************/
    UI.DialogBox = function (useroptions) {
        var options = $.extend({
            title: '提示信息',
            width: '300px',
            parent: true
        }, useroptions);

        if (options.parent) {
            //顶层artDialog对象
            return art.dialog.top.art.dialog(options);
        }
        //当前artDialog对象
        return art.dialog(options);
    };

    /******************************* 
    * 弹出iframe
    * @url :    嵌入iframe的url地址
    * @options: 用户配置项 详细设置参考:http://www.planeart.cn/demo/artDialog/_doc/API.html
    * @cache :  是否开启缓存,默认开启 true/false
    * remark:   操作iframe参考 http://www.planeart.cn/demo/artDialog/_doc/iframeTop.html
     *******************************/
    UI.DialogOpen = function (url, useroptions, cache) {
        var options = $.extend({}, useroptions);

        //当前artDialog对象
        return art.dialog.open(url, options, cache);
    };

    /*******************************
    * 树形控件
    * 使用方法参考:http://www.ztree.me/v3/api.php
    *******************************/
    UI.ZTree = function () {
        return $.fn.zTree;
    }

    /*******************************
    * 日历
    * @useroptions:用户配置项 详细设置参考:http://www.my97.net/dp/demo/index.htm
    *******************************/
    UI.Date = function (useroptions) {
        return WdatePicker(useroptions);
    };

    /*******************************
    * 数据绑定
    *******************************/
    UI.Render = function (table, options) {
        return table.render(options);
    };

    UI.Editor = function (selector, useroptions) {
        var options = $.extend({
            items: [
                'source', '|', 'undo', 'redo', '|', 'preview', 'cut', 'copy', 'paste', 'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright', 'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript', 'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '/', '|', 'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'table', 'anchor', 'link', 'unlink'
            ],
            uploadJson: "/Upload/UploadFile?folder=editor_image",
            resizeType: 1,
            resizeMode: 0,
            allowPreviewEmoticons: false,
            allowImageUpload: true,
            filePostName: "files"
        }, useroptions);

        return KindEditor.create(selector, options);
    };

    /*******************************
   * AJAX等待锁对象遮罩
   * useroptions :  JSON参数对象
   * @obj :         要遮掉的JQUERY DOM对象
   * @opacity:      不透明度 0-1  未公开
   * @bgcolor:      背景颜色  未公开
   * @id :          唯一ID,创建了唯一ID后可以防止重复创建遮罩
   * @zindex:       Z轴深度
   * return :       返回一个对象,对象包含有可调用的Remove方法
   *******************************/
    UI.Mask = function (optionsin) {

        var options = $.extend({
            obj: $('body'),
            opacity: 0.2,
            bgcolor: '#dadada',
            id: 'mask_' + Math.round(Math.random() * 10000000),
            zindex: 99
        }, optionsin);
        var obj = options.obj;
        //不传入对象 
        //如果已存在遮罩 直接退出
        if (typeof obj == 'undefined' || $('#' + options.id).length > 0) return;

        var pageHeight = $(window).height();

        var maxHeight = Math.max(document.documentElement.scrollHeight, document.documentElement.clientHeight);
        if (maxHeight < pageHeight) {
            maxHeight = pageHeight;
        }
        var $maskFrame = $(''
            + '<div id="' + options.id + '">'
            + ' <div style="position:absolute;top:0;left:0;height:' + maxHeight +'px;width:100%;"></div>'
            + ' <div class="mask_screen" style="height:' + maxHeight +'px;width:100%;position:absolute;top:0;left:0;color:red;"></div>'
            + ' <div class="mask_content" style="height:' + maxHeight +'px;width:100%;position:absolute;top:0;left:0;">'
            + '     <div style="text-align:center;margin-top:' + maxHeight / 2 + 'px">'
            + '         <div class="loading-spinner fade in" style="width: 200px; margin: 0 auto; z-index: 1050;">'
            + '             <div class="progress progress-striped active">'
            + '                 <div class="progress-bar" style="width: 100%;"></div>'
            + '             </div>'
            + '         </div>'
            + '     </div>'
            + ' </div>'
            + '</div>'
        );

        $maskFrame.css({
            position: 'absolute',
            width: '100%',
            height: '100%',
            top: obj.offset().top,
            top: 0,
            left: 0,
            zIndex: options.zindex
        })

            .find('.mask_screen').css({
                opacity: options.opacity,
                backgroundColor: '#dadada'
            })
            .find('.mask_content').css({
                zIndex: options.zindex
            })
            .find('iframe').css({
                opacity: 0
            });

        obj.append($maskFrame);

        var _overflow = obj.css('overflow');
        obj.css({ overflow: 'hidden' });

        return {
            Remove: function () {
                $maskFrame.remove();
                obj.css({ overflow: _overflow });
            }
        };
    };

    /*============================
    消息框提示
    specilCss:alert-success;alert-danger;alert-info;alert-warning; //弹出的颜色
    word： text  //内容
    =*/
    UI.Tip_alert = function (specilCss, word, left, width) {
        var isShow = 0;
        if (isShow >= 1) {
            return false;
        }
        var html = '<div id="alert" class="alert ' + specilCss + ' alert-dismissible alertbox" style="position:fixed; z-index:999999; top: 0; left:' + left + '%; width:' + width + '%;" role="alert">';
        html += '<button type="button" onclick= "Topro.UI.Tip_delete(this);" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button><strong>' + word + '</strong></div>';

        var jsTipObj = $('.alertbox');
        if (!jsTipObj.hasClass(specilCss)) {
            $("body").prepend(html);
            isShow++;
            setTimeout(function () {
                $('.' + specilCss).animate({
                    opacity: 0
                }, 500, function () {
                    $(this).remove();
                });
            }, 3000);
        } else {
            isShow++;
            return;
        }
    };

    UI.Tip_delete = function (obj) {
        var parentObj = $(obj).parent();
        parentObj.animate({
            opacity: 0
        }, 200);
        setTimeout(function () {
            parentObj.remove();
        }, 200);
    };

    UI.Tip_success = function (word) {
        Topro.UI.Tip_alert("alert-success", word, 35, 35);
    };

    UI.Tip_danger = function (word) {
        Topro.UI.Tip_alert("alert-danger", word, 35, 35);
    };

    UI.Tip_info = function (word) {
        Topro.UI.Tip_alert("alert-info", word, 35, 35);
    };

    UI.Tip_warning = function (word) {
        Topro.UI.Tip_alert("alert-warning", word, 35, 35);
    };


    UI.Tip_short_success = function (word) {
        Topro.UI.Tip_alert("alert-success", word, 2, 96);
    };

    UI.Tip_short_danger = function (word) {
        Topro.UI.Tip_alert("alert-danger", word, 2, 96);
    };

    UI.Tip_short_info = function (word) {
        Topro.UI.Tip_alert("alert-info", word, 2, 96);
    };

    UI.Tip_short_warning = function (word) {
        Topro.UI.Tip_alert("alert-warning", word, 2, 96);
    };

    /*******************************
    * 无权限跳转
    *******************************/
    UI.NoPrivilege = function (type) {

        if (type == 1) {
            self.location.href = "/view/shared/noprivilege.html";
        }
        else {
            Topro.UI.Tip_warning("您没有权限进行此操作");
        }
    };

    /*******************************
    * 超时登录跳转
    *******************************/
    UI.LoginBox = function () {

        Topro.UI.Tip_warning("登录失败,请重新登录");

        if (window.parent != null) {
            setTimeout(function () {
                top.location.href = "/login.html";
            }, 1000);

        } else {
            setTimeout(function () {
                top.location.href = "/login.html";
            }, 1000);
        }
    };

    //数据列表自动高度
    UI.DataAutoHeight = function () {
        $(window).bind('load', function () {
            DataAutoHeight();//table自动高度
        }).bind('resize', function () {//窗口改变
            DataAutoHeight();//table自动高度
        });
        function DataAutoHeight() {

            if ($('.data-scroll').length) {

                var DataBodyTop = $('.data-scroll').offset().top;
                var winH = $(window).height();
                var DataViewH = $('.data-view');
                var DataPageH = $('.data-page').outerHeight();

                DataViewH.css({
                    height: winH - DataBodyTop - DataPageH
                });
            } else {
                return false;
            }

            if ($.fn.slimscroll) {
                $(".data-view").slimscroll({
                    color: "rgba(0,0,0,0.4)",
                    distance: '5px',
                    overflow: 'initial !important'
                });
            }

        }
    };

    UI.Triggerbox = function (options) {
        var defaults = {
            parent: "#accordion",
            clickObj: ".AdvSearchcom",
            panel: ".AdvSearchcom",
            clickEve: null,
            searchCallBack: null,
            cancelCallBack: null
        }
        var opt = $.extend(defaults, options);

        $(opt.btnAdvSearch).click(function () {
            if ($(opt.panel).hasClass("collapse")) {
                $(opt.panel).removeClass("collapse");
            } else {
                $(opt.panel).addClass("collapse");
            }
        });

        $(opt.panel).find("button[id='search']").click(function () {

            $(opt.panel).addClass("collapse");

            if ($.isFunction(opt.searchCallBack)) {
                opt.searchCallBack();
            }
        });

        $(opt.panel).find("button[id='cancel']").click(function () {

            $(opt.panel).addClass("collapse");

            if ($.isFunction(opt.cancelCallBack)) {
                opt.cancelCallBack();
            }
        });
    };

    UI.bootstrapTable = function (options) {

        var defaults = {
            pageNumber: 1,
            pageSize: 10,
        }

        var opt = $.extend(defaults, options);

        $(options.tableId).bootstrapTable({
            url: opt.url,
            method: 'post',
            dataType: "json",
            striped: true,
            pageNumber: 1,
            pageSize: 10,
            pagination: true,
            fixedColumns: true,
            fixedNumber: 1,
            sidePagination: "server",
            queryParamsType: '',
            queryParams: opt.params,
            columns: opt.columns,
            //加载成功时执行
            onLoadSuccess: opt.onLoadSuccess,
            //加载失败时执行
            onLoadError: opt.onLoadSuccess
        });
    }

    /*******************************
    *DataGrid
    @ctrId             控件Id
    @ customOptions:   制参数
    *******************************/
    UI.DataGrid = function (customOptions) {
        return $("#" + customOptions.ctrId).datagrid({
            fit: false,
            loadMsg: '数据加载中，请稍后……',
            method: "post",
            border: true,
            url: customOptions.url,
            queryParams: customOptions.queryParams,
            rownumbers: customOptions.rownumbers,
            pagination: customOptions.pagination,
            singleSelect: customOptions.singleSelect,
            pageSize: customOptions.pageSize,
            pageList: customOptions.pageList,
            height: customOptions.height,
            idField: customOptions.idField,
            frozenColumns: customOptions.frozenColumns,
            columns: customOptions.columns
        });
    };


    UI.I18n = function () {

    };

    //导入到全局Topro中
    Topro.UI = UI;
})(Topro);